package com.example.carconsumer.controller.lwj;

import com.alibaba.dubbo.config.annotation.Reference;
import com.example.carinterface.pojo.ResponseResult;
import com.example.carinterface.service.lwj.uploadPhoto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/business")
@CrossOrigin
@Api(value = "司机端上传图片接口",tags = "司机端上传图片API")
public class UploaderController extends BaseController{
// 调用service层
    @Reference(check = false)
    private uploadPhoto uploadPhotoService;
@ResponseBody
@RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
//文件上传
// 接车仪表盘图片上传
@ApiOperation(value = "接车仪表盘图片上传",notes = "接车仪表盘图片上传",httpMethod = "post")
@ApiImplicitParams({

    @ApiImplicitParam(name = "bussinessId",value = "订单编号",paramType = "query",dataType = "Int",required = true)
})
public void uploadPicture(@RequestParam(value="file",required=false) MultipartFile[] files,HttpServletRequest request,HttpServletResponse response,int bussinessId){
// 定义容器
ResponseResult result = new ResponseResult();
Map<String, Object> map = new HashMap<String, Object>();
// 目标文件
File targetFile=null;
// 定义存储路径
String url=""; //返回存储路径
// 存入数据库的字符串编码
String uploadFileNames="";
int code=1;
int i =1;
System.out.println("参数中得file值"+files);
// 循环遍历
for (MultipartFile file : files) {
    // 获取源文件名
    String fileName=file.getOriginalFilename();
    System.out.println("fileName"+fileName);
// 判断源文件是否存在
    if(fileName!=null&&fileName!=""){
        // 输出服务器得本机地址
        System.out.println("本地路径"+ ClassUtils.getDefaultClassLoader().getResource("").getPath());
        // 存放文件得文件地址
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        // 获取源文件后缀名字
        String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        // 生成新 文件上传后得新的名字+后缀名
        fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
        // 要存放图片的文件夹名字
        File file1 =new File(path+File.separator+"upload"+File.separator+"imges");
        //如果文件夹不存在则创建
        if(!file1 .exists()  && !file1 .isDirectory()){
            file1 .mkdir();
        }
        targetFile = new File(file1, fileName);
        try {
            file.transferTo(targetFile);
            // 存入数据库的名字
            uploadFileNames=uploadFileNames+";"+fileName;
            map.put("filename"+i+":", fileName);
            i++;
        } catch (IOException e) {
            e.printStackTrace();
            code=1;
            result.setCode(code);
            result.setMessage("系统异常，图片上传失败");
        }
    }
}
// 将图片名字存入相应的数据库字段
System.out.println("uploadFileNames"+uploadFileNames);
boolean b = uploadPhotoService.uploadPannlPoto(uploadFileNames, bussinessId);
if (b){
    // 返回保存信息
    code=0;
    result.setCode(code);
    result.setMessage("图片上传成功");
    result.setResult(map);
    writeJson(response, result);
}else{
// 返回信息
    code=1;
    result.setCode(code);
    result.setMessage("图片上传失败，服务器错误");
    writeJson(response, result);
}
}

// 接车外观图片
@RequestMapping(value = "/uploadAppead",method = RequestMethod.POST)
@ApiOperation(value = "接车外观图片",notes = "接车外观图片",httpMethod = "post")
public void uploadAppead(@RequestParam(value="file",required=false) MultipartFile[] files,HttpServletRequest request,HttpServletResponse response,int bussinessId){
// 定义容器
  ResponseResult result = new ResponseResult();
  Map<String, Object> map = new HashMap<String, Object>();
  // 目标文件
  File targetFile=null;
// 定义存储路径
  String url=""; //返回存储路径
  // 存入数据库的字符串编码
  String uploadFileNames="";
  int code=1;
  int i =1;
// 循环遍历
  for (MultipartFile file : files) {
      // 获取源文件名
      String fileName=file.getOriginalFilename();
      System.out.println("fileName"+fileName);
// 判断源文件是否存在
      if(fileName!=null&&fileName!=""){
          // 存放文件得文件地址
          String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
          // 获取源文件后缀名字
          String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
          // 生成新 文件上传后得新的名字+后缀名
          fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
          // 要存放图片的文件夹名字
          File file1 =new File(path+File.separator+"upload"+File.separator+"imges");
          //如果文件夹不存在则创建
          if(!file1 .exists()  && !file1 .isDirectory()){
              file1 .mkdir();
          }
          targetFile = new File(file1, fileName);
          try {
              file.transferTo(targetFile);
              // 存入数据库的名字
              uploadFileNames=uploadFileNames+";"+fileName;
              map.put("filename"+i+":", fileName);
              i++;
          } catch (IOException e) {
              e.printStackTrace();
              code=1;
              result.setCode(code);
              result.setMessage("系统异常，图片上传失败");
          }
      }
  }
// 将图片名字存入相应的数据库字段
  System.out.println("uploadFileNames"+uploadFileNames);
  boolean b = uploadPhotoService.uploadAppead(uploadFileNames, bussinessId);
  if (b){
      // 返回保存信息
      code=0;
      result.setCode(code);
      result.setMessage("图片上传成功");
      result.setResult(map);
      writeJson(response, result);
  }else{
// 返回信息
      code=1;
      result.setCode(code);
      result.setMessage("图片上传失败，服务器错误");
      writeJson(response, result);
  }
}

// 还车仪表盘照片
@RequestMapping(value = "/lastDashboardImg",method = RequestMethod.POST)
@ApiOperation(value = "还车仪表盘照片",notes = "还车仪表盘照片",httpMethod = "post")
    public void lastDashboardImg(@RequestParam(value="file",required=false) MultipartFile[] files,HttpServletRequest request,HttpServletResponse response,int bussinessId){
// 定义容器
        ResponseResult result = new ResponseResult();
        Map<String, Object> map = new HashMap<String, Object>();
        // 目标文件
        File targetFile=null;
// 定义存储路径
        String url=""; //返回存储路径
        // 存入数据库的字符串编码
        String uploadFileNames="";
        int code=1;
        int i =1;
// 循环遍历
        for (MultipartFile file : files) {
            // 获取源文件名
            String fileName=file.getOriginalFilename();
            System.out.println("fileName"+fileName);
// 判断源文件是否存在
            if(fileName!=null&&fileName!=""){
                // 存放文件得文件地址
                String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
                // 获取源文件后缀名字
                String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                // 生成新 文件上传后得新的名字+后缀名
                fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
                // 要存放图片的文件夹名字
                File file1 =new File(path+File.separator+"upload"+File.separator+"imges");
                //如果文件夹不存在则创建
                if(!file1 .exists()  && !file1 .isDirectory()){
                    file1 .mkdir();
                }
                targetFile = new File(file1, fileName);
                try {
                    file.transferTo(targetFile);
                    // 存入数据库的名字
                    uploadFileNames=uploadFileNames+";"+fileName;
                    map.put("filename"+i+":", fileName);
                    i++;
                } catch (IOException e) {
                    e.printStackTrace();
                    code=1;
                    result.setCode(code);
                    result.setMessage("系统异常，图片上传失败");
                }
            }
        }
// 将图片名字存入相应的数据库字段
        System.out.println("uploadFileNames"+uploadFileNames);
        boolean b = uploadPhotoService.lastDashboardImg(uploadFileNames, bussinessId);
        if (b){
            // 返回保存信息
            code=0;
            result.setCode(code);
            result.setMessage("图片上传成功");
            result.setResult(map);
            writeJson(response, result);
        }else{
// 返回信息
            code=1;
            result.setCode(code);
            result.setMessage("图片上传失败，服务器错误");
            writeJson(response, result);
        }
    }


// 还车车辆外观照片
@RequestMapping(value = "/lastCarImg",method = RequestMethod.POST)
@ApiOperation(value = "还车车辆外观照片",notes = "还车车辆外观照片",httpMethod = "post")
public void lastCarImg(@RequestParam(value="file",required=false) MultipartFile[] files,HttpServletRequest request,HttpServletResponse response,int bussinessId){
// 定义容器
 ResponseResult result = new ResponseResult();
 Map<String, Object> map = new HashMap<String, Object>();
 // 目标文件
 File targetFile=null;
// 定义存储路径
 String url=""; //返回存储路径
 // 存入数据库的字符串编码
 String uploadFileNames="";
 int code=1;
 int i =1;
// 循环遍历
 for (MultipartFile file : files) {
     // 获取源文件名
     String fileName=file.getOriginalFilename();
     System.out.println("fileName"+fileName);
// 判断源文件是否存在
     if(fileName!=null&&fileName!=""){
         // 存放文件得文件地址
         String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
         // 获取源文件后缀名字
         String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
         // 生成新 文件上传后得新的名字+后缀名
         fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
         // 要存放图片的文件夹名字
         File file1 =new File(path+File.separator+"upload"+File.separator+"imges");
         //如果文件夹不存在则创建
         if(!file1 .exists()  && !file1 .isDirectory()){
             file1 .mkdir();
         }
         targetFile = new File(file1, fileName);
         try {
             file.transferTo(targetFile);
             // 存入数据库的名字
             uploadFileNames=uploadFileNames+";"+fileName;
             map.put("filename"+i+":", fileName);
             i++;
         } catch (IOException e) {
             e.printStackTrace();
             code=1;
             result.setCode(code);
             result.setMessage("系统异常，图片上传失败");
         }
     }
 }
// 将图片名字存入相应的数据库字段
 System.out.println("uploadFileNames"+uploadFileNames);
 boolean b = uploadPhotoService.lastCarImg(uploadFileNames, bussinessId);
 if (b){
     // 返回保存信息
     code=0;
     result.setCode(code);
     result.setMessage("图片上传成功");
     result.setResult(map);
     writeJson(response, result);
 }else{
// 返回信息
     code=1;
     result.setCode(code);
     result.setMessage("图片上传失败，服务器错误");
     writeJson(response, result);
 }
}

// 行驶证照片照片
@RequestMapping(value = "/licenseImg",method = RequestMethod.POST)
@ApiOperation(value = "行驶证照片照片",notes = "行驶证照片照片",httpMethod = "post")
public void licenseImg(@RequestParam(value="file",required=false) MultipartFile[] files,HttpServletRequest request,HttpServletResponse response,int bussinessId){
// 定义容器
ResponseResult result = new ResponseResult();
Map<String, Object> map = new HashMap<String, Object>();
// 目标文件
File targetFile=null;
// 定义存储路径
String url=""; //返回存储路径
// 存入数据库的字符串编码
String uploadFileNames="";
int code=1;
int i =1;
// 循环遍历
for (MultipartFile file : files) {
    // 获取源文件名
    String fileName=file.getOriginalFilename();
    System.out.println("fileName"+fileName);
// 判断源文件是否存在
    if(fileName!=null&&fileName!=""){
        // 存放文件得文件地址
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        // 获取源文件后缀名字
        String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        // 生成新 文件上传后得新的名字+后缀名
        fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
        // 要存放图片的文件夹名字
        File file1 =new File(path+File.separator+"upload"+File.separator+"imges");
        //如果文件夹不存在则创建
        if(!file1 .exists()  && !file1 .isDirectory()){
            file1 .mkdir();
        }
        targetFile = new File(file1, fileName);
        try {
            file.transferTo(targetFile);
            // 存入数据库的名字
            uploadFileNames=uploadFileNames+";"+fileName;
            map.put("filename"+i+":", fileName);
            i++;
        } catch (IOException e) {
            e.printStackTrace();
            code=1;
            result.setCode(code);
            result.setMessage("系统异常，图片上传失败");
        }
    }
}
// 将图片名字存入相应的数据库字段
System.out.println("uploadFileNames"+uploadFileNames);
boolean b = uploadPhotoService.licenseImg(uploadFileNames, bussinessId);
if (b){
    // 返回保存信息
    code=0;
    result.setCode(code);
    result.setMessage("图片上传成功");
    result.setResult(map);
    writeJson(response, result);
}else{
// 返回信息
    code=1;
    result.setCode(code);
    result.setMessage("图片上传失败，服务器错误");
    writeJson(response, result);
}
}


//年检标照片
@RequestMapping(value = "/inspectAnnually",method = RequestMethod.POST)
@ApiOperation(value = "年检标照片",notes = "年检标照片",httpMethod = "post")
public void inspectAnnually(@RequestParam(value="file",required=false) MultipartFile[] files,HttpServletRequest request,HttpServletResponse response,int bussinessId){
// 定义容器
ResponseResult result = new ResponseResult();
Map<String, Object> map = new HashMap<String, Object>();
// 目标文件
File targetFile=null;
// 定义存储路径
String url=""; //返回存储路径
// 存入数据库的字符串编码
String uploadFileNames="";
int code=1;
int i =1;
// 循环遍历
for (MultipartFile file : files) {
    // 获取源文件名
    String fileName=file.getOriginalFilename();
    System.out.println("fileName"+fileName);
// 判断源文件是否存在
    if(fileName!=null&&fileName!=""){
        // 存放文件得文件地址
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        // 获取源文件后缀名字
        String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        // 生成新 文件上传后得新的名字+后缀名
        fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
        // 要存放图片的文件夹名字
        File file1 =new File(path+File.separator+"upload"+File.separator+"imges");
        //如果文件夹不存在则创建
        if(!file1 .exists()  && !file1 .isDirectory()){
            file1 .mkdir();
        }
        targetFile = new File(file1, fileName);
        try {
            file.transferTo(targetFile);
            // 存入数据库的名字
            uploadFileNames=uploadFileNames+";"+fileName;
            map.put("filename"+i+":", fileName);
            i++;
        } catch (IOException e) {
            e.printStackTrace();
            code=1;
            result.setCode(code);
            result.setMessage("系统异常，图片上传失败");
        }
    }
}
// 将图片名字存入相应的数据库字段
System.out.println("uploadFileNames"+uploadFileNames);
boolean b = uploadPhotoService.inspectAnnually(uploadFileNames, bussinessId);
if (b){
    // 返回保存信息
    code=0;
    result.setCode(code);
    result.setMessage("图片上传成功");
    result.setResult(map);
    writeJson(response, result);
}else{
// 返回信息
    code=1;
    result.setCode(code);
    result.setMessage("图片上传失败，服务器错误");
    writeJson(response, result);
}
}























//文件下载
@RequestMapping(value = "/download",method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "文件下载",notes = "文件下载",httpMethod = "get", response = String.class)
@ApiImplicitParam(name = "filename",value = "图片名字",required = true,dataType = "String",paramType = "query")
public String download(HttpServletRequest request,HttpServletResponse response) throws IOException
{
    //获取本地路径
    String path= ClassUtils.getDefaultClassLoader().getResource("").getPath();
    // 获取要请求得图片名
    String fileName=request.getParameter("filename");
    System.out.println("请求得图片名字"+fileName);
    //  定位到请求得图片
    File file=new File(path+File.separator+"upload"+File.separator+"imges"+File.separator+fileName);
    // 判断请求资源是否存在
    if(file.exists()){
        //设置MIME类型
        response.setContentType("application/octet-stream");
        //或者为response.setContentType("application/x-msdownload");
        //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
        response.addHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes(), "utf-8"));
        // 开启流 向前端传输
        InputStream inputStream=new FileInputStream(file);
        ServletOutputStream outputStream=response.getOutputStream();
        byte[] bs=new byte[1024];
        while((inputStream.read(bs)>0)){
            outputStream.write(bs);
        }
        outputStream.close();
        inputStream.close();
}else{
        return "文件不存在";
    }
    return "文件传输完成";
}















// 删除图片
@RequestMapping(value = "/delete",method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "删除图片接口",notes = "删除图片",httpMethod = "get", response = String.class)
@ApiImplicitParam(name = "filename",value = "删除图片名字",required = true,dataType = "String",paramType = "query")
public void delete(HttpServletRequest request,HttpServletResponse response)
{
ResponseResult responseResult = new ResponseResult();
Map<String, Object> map = new HashMap<String, Object>();
//获取删除图片名字
String fileName=request.getParameter("filename");
//获取本地路径
String path= ClassUtils.getDefaultClassLoader().getResource("").getPath();
// 生成文件对象
File file=new File(path+File.separator+"upload"+File.separator+"imges"+File.separator+fileName);
//   判断文件是否存在
if(file.exists()&&file.delete()){
    responseResult.setCode(0);
    responseResult.setMessage("删除成功");
}else{
    responseResult.setCode(1);
    responseResult.setMessage("删除失败");
}
writeJson(response, responseResult);
}





























}
